package com.jjc.MyWebApp.Service;

import com.jfinal.aop.Before;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jjc.MyWebApp.Annotation.Service;
import com.jjc.MyWebApp.Constant.CacheConstant;
import com.jjc.MyWebApp.Constant.ConfigConstant;
import com.jjc.MyWebApp.Constant.UserConstant;
import com.jjc.MyWebApp.Interceptor.AuthInterceptor;
import com.jjc.MyWebApp.Model.User;
import com.jjc.MyWebApp.Model.Userinfo;
import com.jjc.MyWebApp.Routes.BaseController;
import com.jjc.MyWebApp.kit.DateKit;
import com.jjc.MyWebApp.kit.IDEAKit;
import com.jjc.MyWebApp.kit.Pbkdf2Kit;
import org.apache.commons.codec.binary.Base64;

import java.util.Date;

/**
 * Created by jiaji on 2017/5/10.
 */
@Service("userService")
public class UserService extends BaseService {

    private BaseService baseService;
    private static User userDao = User.dao;



    /**
     * 保存新增用户
     * @param ID
     * @param Pwd
     * @param user
     */
    @Before(Tx.class)
    public boolean insert(String ID, String Pwd, User user) {
        //密码加密
        byte[] salt = Pbkdf2Kit.generateSalt();//生成密码盐
        byte[] encryptedPassWord = Pbkdf2Kit.getEncryptedPwd(Pwd,salt);
        user.setUserSalt(Base64.encodeBase64String(salt));
        user.setUserPwd(Base64.encodeBase64String(encryptedPassWord));

        //初始化用户私钥
        user.setUserSecuritykey(Base64.encodeBase64String(IDEAKit.initKey().getEncoded()));
        user.setUserId(ID);

        user.setUserName("新用户");
        user.setUserStartdate(new Date());
        user.setUserOrder(0);
        boolean lock =user.save() && new Userinfo().setUserinfoId(ID).save();
        if (lock) CacheUpdateById(ID);
        return lock;
    }

    public int login(BaseController controller, String email, String password, boolean autoLogin) {
        //根据Email取用户
        User user = CacheGetUserByEmail(email);
        if (null == user)
            return UserConstant.User_Login_info_0;

        //判断用户是否启用
        if (user.getUserStatus() == 0)
            return UserConstant.User_Login_info_1;

        //判断用户密码错误次数超限
        if (user.getUserErrcount() >= PropKit.getInt(ConfigConstant.config_pwd_ErrorCount)) {
            int hour = DateKit.getDateHourSpace(user.getUserStopdate(), new Date());
            int passErrorHour = PropKit.getInt(ConfigConstant.config_pwd_ErrorHour);
            if (hour < passErrorHour)
                return UserConstant.User_Login_info_2;
        }

        //验证密码
        byte[] salt = Base64.decodeBase64(user.getUserSalt());//用户私钥
        byte[] encryptedPassword = Base64.decodeBase64(user.getUserPwd());//密文
        boolean lock = Pbkdf2Kit.authenticate(password, encryptedPassword, salt);
        if (lock) {
            //验证通过
            if (user.getUserErrcount() != 0) {
                user.setUserStopdate(null);
                user.setUserErrcount(0);
                user.update();
                user=CacheUpdateById(user.getUserId());
            }
            AuthInterceptor.setCurrentUser(controller,user,autoLogin);
            return UserConstant.User_Login_info_4;
        }else{
            //验证未通过
            user.setUserStopdate(new Date());
            user.setUserErrcount(user.getUserErrcount()+1);
            user.update();
            user=CacheUpdateById(user.getUserId());
            return UserConstant.User_Login_info_3;
        }

    }

    /**
     * 通过邮箱地址在缓存中查找用户
     *
     * @param Email
     * @return User
     */
    public  User CacheGetUserByEmail(final String Email) {
        return userDao.findFirstByCache(
                CacheConstant.UserCacheName,
                CacheConstant.prefixUserEmail + Email,
                userDao.getSql("User.findUserByEmail"),
                Email);
    }
    /**
     * 通过用户ID在缓存中查找用户
     *
     * @param id
     * @return User
     */
    public  User CacheGetUserById(final String id) {
        return userDao.findFirstByCache(
                CacheConstant.UserCacheName,
                CacheConstant.prefixUserId + id,
                userDao.getSql("User.findUserByid"),
                id);
    }

    /**
     * 添加 OR 更新缓存<br/>
     * 在缓存中添加或更新以主键为关键字的数据<br/>
     * 在缓存中添加或更新以邮箱为关键字的数据<br/>
     * @param id    user_id
     * @return      User
     */
    public  User CacheUpdateById(String id) {
        User user = userDao.findFirst(userDao.getSql("User.findUserByid"), id);
        if (null != user) {
            CacheKit.put(CacheConstant.UserCacheName, CacheConstant.prefixUserId + id, user);
            CacheKit.put(CacheConstant.UserCacheName, CacheConstant.prefixUserId + user.getUserEmail(), user);
        }
        return user;
    }


    public boolean insert(Model T) {
        return false;
    }

    public boolean update(Model T) {
        return false;
    }

    public boolean remove(String ID) {
        return false;
    }

}
